package generate

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"

	"github.com/c-bata/go-prompt"
)

func Cli() {
	preparedWords := []prompt.Suggest{
		{
			Text:        ",",
			Description: "Sep",
		},
		{
			Text:        "P, R2",
			Description: "suggest mode file + random(2)",
		},
		{
			Text:        "P, S2",
			Description: "suggest mode file + symbol(2)",
		},
		{
			Text:        "W, S2",
			Description: "suggest mode web words + symbol(2)",
		},
		{
			Text:        "D1",
			Description: "Digtal len 1",
		},
		{
			Text:        "S1",
			Description: "symbol len 1",
		},

		{
			Text:        "P",
			Description: "extend",
		},
		{
			Text:        "R4",
			Description: "random num 4 from digest or symbol",
		},
		{
			Text:        "W",
			Description: "craw text from html url remote!",
		},
		{
			Text:        "exit",
			Description: "exit all",
		},
	}
	modeStr := prompt.Input("Generate Password Mode S D P sep by , >>", func(d prompt.Document) []prompt.Suggest {

		return prompt.FilterHasPrefix(preparedWords, d.GetWordBeforeCursor(), true)
	})
	if modeStr == "exit" {
		return
	}
	modeStr = strings.ToUpper(modeStr)
	fileName := ""
	if strings.Contains(modeStr, "P") {

		var s []prompt.Suggest
		fileName = prompt.Input("File >", func(d prompt.Document) []prompt.Suggest {

			text := d.TextBeforeCursor()
			if strings.Contains(text, "/") || strings.Contains(text, "\\") {
				text = filepath.Dir(text)

			}
			fs, err := ioutil.ReadDir(text)

			if err == nil {
				for _, f := range fs {
					s = append(s, prompt.Suggest{
						Text:        filepath.Join(text, f.Name()),
						Description: fmt.Sprintf("is dir:%v", f.IsDir()),
					})
				}
			} else {
				fs, _ := ioutil.ReadDir(".")
				for _, f := range fs {
					s = append(s, prompt.Suggest{
						Text:        filepath.Join(text, f.Name()),
						Description: fmt.Sprintf("is dir:%v", f.IsDir()),
					})
				}
			}
			return prompt.FilterHasPrefix(s, text, true)
		})
		if _, err := os.Stat(fileName); err != nil {
			log.Fatal("load password file error")
		}
	}
	outputFile := prompt.Input("output file name >", func(d prompt.Document) (m []prompt.Suggest) {
		m = append(m, prompt.Suggest{
			Text: "output.txt",
		})
		return prompt.FilterHasPrefix(m, d.GetWordBeforeCursor(), true)
	})
	if fc := GeneratePassword(outputFile, modeStr, fileName); fc > 0 {
		log.Println("generate success , len:", fc, "in :", outputFile)
	}
}

func GetUri() (uri string) {
	uri = prompt.Input("http url to get >", func(d prompt.Document) (m []prompt.Suggest) {
		m = append(m, prompt.Suggest{
			Text: "http://",
		})
		m = append(m, prompt.Suggest{
			Text: "https://",
		})
		return prompt.FilterHasPrefix(m, d.GetWordBeforeCursor(), true)
	})
	return
}
